//
//  WCINumberPassword.m
//  WCImApp
//
//  Created by WCImApp on 2019/9/9.
//  Copyright © 2019 WCImApp. All rights reserved.
//

#import "WCINumberPassword.h"
#import "WHC_PswInputView.h"
#import "WHC_NumberPlateView.h"

#import "CoreLockConst.h"
#define titleTopMargin 60.0
@interface WCINumberPassword () <WHC_NumberPlateViewDelegate>

@property (nonatomic, strong) UIButton *closeBtn;
@property (nonatomic, strong) UILabel *errorTipLab;
//密码输入视图
@property (nonatomic, strong) WHC_PswInputView *pswInputView;
//数字按钮视图
@property (nonatomic, strong) WHC_NumberPlateView *numberPlateView;
@property (nonatomic, strong) UIButton *toolBtn;

@property (nonatomic, copy) NSString *psdRecord;
@property (nonatomic, copy) NSString *firstPsd;
//验证密码时，密码验证对错的状态
@property (nonatomic, assign) BOOL modify_VeriryOldRight;

@end

@implementation WCINumberPassword

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setUI];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}


#pragma mark - Private Methods

- (void)setUI {
//    _closeBtn = [[UIButton alloc] init];
//    [_closeBtn setImage:[MOModuleService imageNamed:@"nav_icon_close_black"] forState:UIControlStateNormal];
//    [_closeBtn addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self addSubview:_closeBtn];
    
    _headerBtn = [[UIButton alloc] init];
    _headerBtn.layer.masksToBounds = YES;
    _headerBtn.layer.cornerRadius = 8;
//    _headerBtn.layer.borderColor = [UIColor whiteColor].CGColor;
//    _headerBtn.layer.borderWidth = 1;
    _headerBtn.hidden = YES;
    [self addSubview:_headerBtn];
    
    _errorTipLab = [[UILabel alloc] init];
    _errorTipLab.font = WCIFontMedium(14);
    _errorTipLab.textColor = mp_main_text_color;
    _errorTipLab.numberOfLines = 0;
    _errorTipLab.textAlignment = NSTextAlignmentCenter;
    _errorTipLab.text = (@"请输入密码");
    [self addSubview:_errorTipLab];
    
    _pswInputView = [[WHC_PswInputView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.5 - WCI_ScaleWidth(311) * 0.5, 0.22*SCREEN_HEIGHT +WCI_IPHONE_STATUSBAR_HEIGHT, WCI_ScaleWidth(311), 9)];
    _pswInputView.height = 9;
    [self addSubview:_pswInputView];
    
//    CGFloat numberPlateViewY = self.view.height - KWHC_BottomHeight - [WHC_PlateView plateHeightWithType:ClickNumberType];
    _numberPlateView = [[WHC_NumberPlateView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.5 - WCI_ScaleWidth(311) * 0.5, 0.3 *SCREEN_HEIGHT +WCI_IPHONE_STATUSBAR_HEIGHT, WCI_ScaleWidth(311), [WHC_PlateView plateHeightWithType:ClickNumberType])];
    _numberPlateView.delegate = self;
    [self addSubview:_numberPlateView];
    
//    _toolBtn = [[UIButton alloc] init];
//    _toolBtn.titleLabel.font = [UIFont systemFontOfSize:14];
//    [_toolBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
//    [self addSubview:_toolBtn];
    
//    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self).offset(16);
//        make.top.equalTo(self).offset(WCI_IPHONE_STATUSBAR_HEIGHT);
//        make.height.width.mas_equalTo(44);
//    }];
    
    [_headerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.top.equalTo(self).offset(WCI_IPHONE_STATUSBAR_HEIGHT + 0.068 *SCREEN_HEIGHT);
        make.width.height.mas_equalTo(64);
    }];
    
    [_errorTipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.right.mas_offset(-16);
        make.top.equalTo(self.headerBtn.mas_bottom).offset(10);
    }];
    
//    [_pswInputView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.errorTipLab.mas_bottom).offset(22);
//        make.centerX.width.equalTo(self);
//        make.height.mas_equalTo(9);
//    }];
//
//    [_numberPlateView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.width.equalTo(self);
//        make.top.equalTo(self.pswInputView.mas_bottom).offset(32);
//        make.height.mas_equalTo([WHC_PlateView plateHeightWithType:ClickNumberType]);
//    }];

//    [_toolBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(self);
//        make.bottom.equalTo(self).offset(-60);
//        make.width.mas_equalTo(90);
//        make.height.mas_equalTo(35);
//    }];
}

- (void)touchIDHiddenState:(BOOL)state{
    [_numberPlateView touchIDHiddenState:state];
}

- (void)updateConstraintsWhenLocalAuth{
    _pswInputView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - WCI_ScaleWidth(311) * 0.5, [self tipLabMaxY] + WCI_ScaleWidth(33) + 32 + 14 + 14 , WCI_ScaleWidth(311), 9);
    _numberPlateView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - WCI_ScaleWidth(311) * 0.5,CGRectGetMaxY(self.pswInputView.frame) + WCI_ScaleWidth(20), WCI_ScaleWidth(311), [WHC_PlateView plateHeightWithType:ClickNumberType]);
}

- (CGFloat)tipLabMaxY{
    return WCI_IPHONE_STATUSBAR_HEIGHT + 0.068 *SCREEN_HEIGHT + 64 + 10 + 14;
}
- (void)updateContent {
    [_errorTipLab mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(WCI_ScaleWidth(55) + WCI_IPHONE_NAVIGATIONBAR_HEIGHT);
    }];
    _pswInputView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - WCI_ScaleWidth(311) * 0.5, WCI_ScaleWidth(102) + WCI_IPHONE_NAVIGATIONBAR_HEIGHT, WCI_ScaleWidth(311), 9);
    _numberPlateView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - WCI_ScaleWidth(311) * 0.5, WCI_ScaleWidth(174) + WCI_IPHONE_NAVIGATIONBAR_HEIGHT, WCI_ScaleWidth(311), [WHC_PlateView plateHeightWithType:ClickNumberType]);
}

- (void)showErrorAnimat {
    [self.pswInputView showMistakeMsg];
}

/**
 *  提示语修改
 *  @param  content 修改的内容
 *  @param  isError 是否是错误状态的内容提示（对应展示错误的提示样式）
 */
- (void)tipEditWithContent:(NSString *)content isError:(BOOL)isError {
    if (isError) {
        self.errorTipLab.textColor = CoreLockWarnColor;//CoreLockWarnColor;
    } else {
        self.errorTipLab.textColor = mp_main_text_color;//CoreLockNormalTextColor;
    }
    
    self.errorTipLab.text = content;
}

/**
 *  还原至初始状态
 */
- (void)revertToTheOriginalStateWithClearTime:(CGFloat)clearTime {
    WeakSelf(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(clearTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weakSelf.psdRecord = @"";
        [weakSelf.numberPlateView clearClickCount];
        [weakSelf.pswInputView clearAllPswCircle];
    });
}

#pragma mark - WHC_NumberPlateViewDelegate

- (void)WHC_NumberPlateView:(WHC_NumberPlateView *)numberPlateView clickIndex:(NSInteger)index didFinish:(BOOL)finish {
    WeakSelf(ws);
    if (finish) {
        self.psdRecord = [self.psdRecord stringByAppendingString:[NSString stringWithFormat:@"%ld",index]];
        self.psdRecord = [self.psdRecord substringToIndex:6];
        [self.pswInputView addPswCircleFinish:^{
            switch (weakSelf.type) {
                case MOLockType_Set:
                case MOLockType_FirstSet:
                {
                    //开始
                    if (weakSelf.firstPsd == nil) {
                        //第一次输入
                        if (!weakSelf.isLocal) {
                            //新旧密码相同
                            if ([weakSelf.beforePsd isEqualToString:weakSelf.psdRecord]) {
                                [weakSelf.pswInputView showMistakeMsg];
                                [weakSelf revertToTheOriginalStateWithClearTime:1];
                                if (weakSelf.callBackSamePasswordAboutNewAndLocal) {
                                    weakSelf.callBackSamePasswordAboutNewAndLocal();
                                    return;
                                }
                            }
                        }
                        
                        weakSelf.firstPsd = weakSelf.psdRecord;
                        [weakSelf revertToTheOriginalStateWithClearTime:0];
                        if (weakSelf.callBackFirstInputPassword) {
                            weakSelf.callBackFirstInputPassword();
                        }
                    } else {
                        //确认
                        if ([weakSelf.firstPsd isEqualToString:weakSelf.psdRecord]) {
                            //两次密码输入相同
                            if (weakSelf.callBackTwicePasswordSame) {
                                weakSelf.callBackTwicePasswordSame(weakSelf.psdRecord);
                            }
                        } else {
                            //两次密码输入不相同
                            [weakSelf.pswInputView showMistakeMsg];
                            [weakSelf.numberPlateView clearClickCount];
                            if (weakSelf.callBackTwicePasswordDifferent) {
                                weakSelf.callBackTwicePasswordDifferent();
                            }
                        }
                    }
                }
                    break;
                case MOLockType_Verify:
                {
                    if (weakSelf.isLocal) {
                        NSString *localPsd = [CoreArchive strForKey:WCICache.user.userId];
                        if ([localPsd isEqualToString:weakSelf.psdRecord]) {
                            //验证密码正确
                            weakSelf.modify_VeriryOldRight = YES;
                            if (weakSelf.callBackVerifyPasswordSuccess) {
                                weakSelf.callBackVerifyPasswordSuccess(weakSelf.psdRecord);
                            }
                        } else {
                            //验证密码错误
                            weakSelf.modify_VeriryOldRight = NO;
                            [weakSelf.pswInputView showMistakeMsg];
                            if (weakSelf.callBackVerifyPasswordFalied) {
                                weakSelf.callBackVerifyPasswordFalied();
                            }
                        }
                    } else {
                        if (weakSelf.callBackToVerufyPassword) {
                            weakSelf.callBackToVerufyPassword(weakSelf.psdRecord);
                        }
                    }
                }
                    break;
                case MOLockType_Modify:
                {
                    if (weakSelf.isLocal) {
                        NSString *localPsd = [CoreArchive strForKey:WCICache.user.userId];
                        if (!weakSelf.modify_VeriryOldRight) {
                            if ([localPsd isEqualToString:weakSelf.psdRecord]) {
                                //验证密码正确
                                weakSelf.modify_VeriryOldRight = YES;
                                [weakSelf revertToTheOriginalStateWithClearTime:0];
                                if (weakSelf.callBackVerifyPasswordSuccess) {
                                    weakSelf.callBackVerifyPasswordSuccess(weakSelf.psdRecord);
                                }
                            } else {
                                //验证密码错误
                                weakSelf.modify_VeriryOldRight = NO;
                                [weakSelf.pswInputView showMistakeMsg];
                                [weakSelf revertToTheOriginalStateWithClearTime:1];
                                if (weakSelf.callBackVerifyPasswordFalied) {
                                    weakSelf.callBackVerifyPasswordFalied();
                                }
                            }
                            
                            return;
                        }
                        
                        if (weakSelf.firstPsd == nil) {
                            //新旧密码相同
                            if ([localPsd isEqualToString:weakSelf.psdRecord]) {
                                [weakSelf.pswInputView showMistakeMsg];
                                [weakSelf revertToTheOriginalStateWithClearTime:1];
                                if (weakSelf.callBackSamePasswordAboutNewAndLocal) {
                                    weakSelf.callBackSamePasswordAboutNewAndLocal();
                                }
                            } else {
                                weakSelf.firstPsd = weakSelf.psdRecord;
                                [weakSelf revertToTheOriginalStateWithClearTime:0];
                                if (weakSelf.callBackFirstInputPassword) {
                                    weakSelf.callBackFirstInputPassword();
                                }
                            }
                        } else {
                            //确认
                            if ([weakSelf.firstPsd isEqualToString:weakSelf.psdRecord]) {
                                //两次密码输入相同
                                if (weakSelf.callBackTwicePasswordSame) {
                                    weakSelf.callBackTwicePasswordSame(weakSelf.psdRecord);
                                }
                            } else {
                                //两次密码输入不相同
                                [weakSelf.pswInputView showMistakeMsg];
                                [weakSelf revertToTheOriginalStateWithClearTime:1];
                                if (weakSelf.callBackTwicePasswordDifferent) {
                                    weakSelf.callBackTwicePasswordDifferent();
                                }
                            }
                        }
                    } else {
                        if (weakSelf.callBackToVerufyPassword) {
                            weakSelf.callBackToVerufyPassword(weakSelf.psdRecord);
                        }
                    }
                }
                    break;
                    
                default:
                    break;
            }
        }];
    } else {
        if (index == 999) {
            [self.pswInputView deletePswCircleFinish:nil];
            if (![QAStringTool isBlankString:self.psdRecord]) {
                self.psdRecord = [self.psdRecord substringToIndex:self.psdRecord.length - 1];
            }
        } else {
            [self.pswInputView addPswCircleFinish:nil];
            if ([QAStringTool isBlankString:self.psdRecord]) {
                self.psdRecord = [NSString stringWithFormat:@"%ld",index];
            } else {
                self.psdRecord = [self.psdRecord stringByAppendingString:[NSString stringWithFormat:@"%ld",index]];
            }
        }
    }
}

- (void)WHC_NumberPlateView:(WHC_NumberPlateView *)numberPlateView startInput:(BOOL)startInput {
    if (startInput) {
        if (self.callBackStartInput) {
            self.callBackStartInput();
        }
    }
}

- (void)WHC_NumberPlateViewTouchIDClicked:(WHC_NumberPlateView *)numberPlateView{
    if (self.callBackTouchIDClicked) {
        self.callBackTouchIDClicked();
    }
}

@end
